package com.yzw.service;

import com.alibaba.fastjson.JSON;
import com.yzw.controller.PostBody;
import com.yzw.dao.AsyncTaskDao;
import com.yzw.dao.BussinessSystemRelationDao;
import com.yzw.dao.entity.AsyncTaskEntity;
import com.yzw.dao.entity.BussinessSystemRelationEntity;
import com.yzw.util.RedisMqBody;
import com.yzw.util.RedisUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yzw
 * @date 2022/8/24 20:39
 * @desc 异步请求push请求服务
 */
@Service
public class AsyncService {
    @Resource
    private BussinessSystemRelationDao bussinessSystemRelationDao;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private AsyncTaskDao asyncTaskDao;
    public boolean post(PostBody body){
        // 根据业务id查询需要分发到的系统处理集合
        String bussinessId = body.getBussinessId();
        List<BussinessSystemRelationEntity> bussinessSystemRelationEntities = bussinessSystemRelationDao.findByBussinessId(bussinessId);
        // 插入任务表  分布式的话这里就要另外看来，本次不考虑
        List<AsyncTaskEntity> asyncTaskEntityList = convert2AsynTaskEntity(bussinessSystemRelationEntities, body.getSourceId());
        asyncTaskDao.insertBatchEntity(asyncTaskEntityList);
        List<Long> asynTaskIdList = asyncTaskDao.findBySourceId(body.getSourceId());
        // push到redis上
        for (Long id : asynTaskIdList) {
            RedisMqBody redisMqBody = new RedisMqBody();
            redisUtil.rpush("redisMqTestKey", JSON.toJSONString(redisMqBody));
        }
        return true;
    }

    private List<AsyncTaskEntity> convert2AsynTaskEntity(List<BussinessSystemRelationEntity> bussinessSystemRelationEntities, String sourceId) {
        if(CollectionUtils.isEmpty(bussinessSystemRelationEntities)){
            return null;
        }
        List<AsyncTaskEntity> asyncTaskEntityList = new ArrayList<>(bussinessSystemRelationEntities.size());
        for (BussinessSystemRelationEntity bussinessSystemRelationEntity : bussinessSystemRelationEntities) {
            AsyncTaskEntity entity = new AsyncTaskEntity();
            entity.setSourceId(sourceId);
            entity.setTargetSystemId(bussinessSystemRelationEntity.getTargetSystemId());
            entity.setBussinessId(bussinessSystemRelationEntity.getBussinessId());
            entity.setSuccess(0);
            entity.setRetryNum(0);
            asyncTaskEntityList.add(entity);
        }
        return asyncTaskEntityList;
    }
}
